<?php

namespace App\Models\Activity;

use Carbon\Carbon;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Support\Facades\Redis as Redis;

class StoreGift extends Model
{

    protected $table = 'store_gift';

    protected $primaryKey = 'activity_id';

    public $timestamps = false;

    public $incrementing = false;

    //获取当前正在进行的活动
    public static function getCache() {

        $save_data = redisTransformation(Redis::get('G_WDH_STORE_GIFT'));

        if ( empty( $save_data )) {

            $where = [
                [ 'start_time' , '<=' , Carbon::now() ],
                [ 'end_time' , '>=' , Carbon::now() ],
                [ 'useFlg' , '=' , 1 ]
            ];

            $activity_data = self::where($where)->orderBy('sort' , 'desc')->first();
            if ( empty( $activity_data ) ) {
                return null;
            }

            $activity_data = $activity_data->toArray();

            $activity_data['extend'] = json_decode( $activity_data['extend'] , true );

            //返回数据
            $save_data = [
                'activity_name' => isset( $activity_data['activity_name'] ) ? $activity_data['activity_name'] : '' ,
                'activity_id' => isset( $activity_data['activity_id'] ) ? $activity_data['activity_id'] : 0 ,
                'template_id' => isset( $activity_data['extend']['template_id'] ) ? $activity_data['extend']['template_id'] : 0 ,
                'template_pic' => isset( $activity_data['extend']['template_pic'] ) ? $activity_data['extend']['template_pic'] : '' ,
                'platform' => isset( $activity_data['extend']['platform'] ) ? $activity_data['extend']['platform'] : [] ,
                'mall_type' => isset( $activity_data['extend']['mall_type'] ) ? $activity_data['extend']['mall_type'] : 1 ,
                'mall_group_id' => isset( $activity_data['extend']['mall_group_id'] ) ? $activity_data['extend']['mall_group_id'] : 0 ,
                'start_time' => isset( $activity_data['start_time'] ) ? $activity_data['start_time'] : '' ,
                'receive_status' => $activity_data['receive_status']
            ];

            //保存redis
            $save_time = strtotime($activity_data['end_time']) - strtotime( Carbon::now() );

            Redis::setex( 'G_WDH_STORE_GIFT' , $save_time , redisTransformation( $save_data , 'set' , $save_time ));

        }

        return $save_data;

    }

}